package com.springcloud.common.web.handler;

import com.springcloud.common.core.entity.R;
import com.springcloud.common.core.exception.ApiErrorCode;
import com.springcloud.common.core.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartException;

/**
 * <p> 默认异常处理  </p>
 *
 * @author mori
 * @since 10/29/2019 10:56 AM
 */
@Slf4j
public class DefaultExceptionHandler {

    @ExceptionHandler(value = {MultipartException.class})
    public R uploadFileLimitException(MultipartException ex) {
        log.error("upload file size limit:{}", ex.getMessage());
        return R.failed(ApiErrorCode.UPLOAD_FILE_SIZE_LIMIT);
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R serviceException(MethodArgumentNotValidException ex) {
        log.error("service exception:{}", ex.getMessage());
        return R.failed(ApiErrorCode.ARGUMENT_NOT_VALID);
    }


    @ExceptionHandler(value = {ApiException.class})
    public R baseException(ApiException ex) {
        log.error("api exception:{}", ex.getMessage());
        return R.failed(ex.getMessage());
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R exception(Exception ex) {
        log.error("exception:{}", ex.getMessage());
        return R.failed(ApiErrorCode.FAILED);
    }

    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R throwable(Throwable throwable) {
        log.error("throwable:{}", throwable.getMessage());
        return R.failed(ApiErrorCode.FAILED);
    }
}
